﻿using Inovout.Component;
using Inovout.Runtime;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace Inovout.Web.Mvc
{
    public static class PermissionHelp
    {
        private static readonly ConcurrentDictionary<PermissonFilterCachedKey, string> queryCache
= new ConcurrentDictionary<PermissonFilterCachedKey, string>();

        public static bool CheckPermisson(string url, string method)
        {
            PermissonFilterCachedKey key = new PermissonFilterCachedKey(url, method);
            var rolesQuery = queryCache.GetOrAdd(key, _ =>
            {
                HttpClient httpClient = new HttpClient();
                httpClient.MaxResponseContentBufferSize = 256000;
                httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36");
                string encodePrivilegeUrl = HttpUtility.UrlEncode(url);
                string checkUrl = ComponentRegistry.Resolve<IApplication>().Properties["client.privilege"].TrimEnd('/') + "?url=" + encodePrivilegeUrl + "&radom=" + new Random().Next(0, 10);
                HttpResponseMessage response = httpClient.GetAsync(new Uri(checkUrl)).Result;
                string roles = response.Content.ReadAsStringAsync().Result;
                return roles;
            });
            string[] rolearry = rolesQuery.Split(',');
            if (rolearry.Length == 0)
            {
                return false;
            }
            else
            {
                Claim roleClaim = (Thread.CurrentPrincipal.Identity as ClaimsIdentity).FindFirst(Constants.RoleClaimType);
                if (roleClaim == null)
                {
                    return false;
                }
                string rolestr = roleClaim.Value;
                for (int i = 0; i < rolearry.Length; i++)
                {
                    if (rolestr.Split(',').Contains(rolearry[i]))
                    {
                        return true;
                    }

                }

            }
            return false;
        }
    }

}
